/*
* $Id: LastInspectOperation.cpp 2 2009-12-23 13:58:02Z volok-aleksej@yandex.ru $
*
* Copyright 2009 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include "LastInspectOperation.h"
#include "../SqlBinder.h"
#include "../Result.h"
#include "../Tables/JournalTable.h"
#include "../Tables/InspectTable.h"
#include "../Tables/TableNames.h"

CLastInspectOperation::CLastInspectOperation(){}
CLastInspectOperation::~CLastInspectOperation(){}

IResult* CLastInspectOperation::GetValue(IDatabase* pDatabase){
	CSqlBinder binder;
	std::tstring strRequest(_T("SELECT id_journal, is_queen_bee, frame, strength, wax, max(date) FROM "));
	if(m_content.s_nIdFamily){
		binder.SetRequest(strRequest + JOURNAL_TABLE_NAME + _T(" WHERE id_family=?"));
		binder.SetValue(0, m_content.s_nIdFamily);
	}else
		binder.SetRequest(strRequest + JOURNAL_TABLE_NAME);
	m_content.Clear();
	IResult* result =  FillContent(pDatabase->ExecRequest(binder.GetRequest()));
	if(!result->GetSizeResult()){
		result->Free();
		return new CResult(std::vector<IOperation::i_content*>());
	}
	content* lastInspect = ((content*)(*result)[0]);
	if(!lastInspect->s_nIdJournal){
		result->Free();
		return new CResult(std::vector<IOperation::i_content*>());
	}
	CInspectTable inspect;
	inspect.m_content.s_nIdJournal = lastInspect->s_nIdJournal;
	IResult* res = inspect.GetValue(pDatabase);
	for(int i = 0; i < (int)res->GetSizeResult(); i++){
		CInspectTable::content* pContent = (CInspectTable::content*)(*res)[i];
		lastInspect->s_nBrood += pContent->s_nBrood;
		lastInspect->s_nHoney += pContent->s_nHoney;
		lastInspect->s_nHousing++;
	}
	res->Free();
	return result;
}

IOperation::i_content* CLastInspectOperation::CreateContent(){
	return new content;
}
CLastInspectOperation::content::content(){
	Clear();
}
void CLastInspectOperation::content::Clear(){
	s_nIdJournal = 0;
	s_nIdFamily = 0;
	s_nFrame = 0;
	s_nStrength = 0;
	s_nHoney = 0;
	s_nHousing = 0;
	s_nBrood = 0;
	s_nWax = 0;
	s_bQueenBee = 0;
}

void CLastInspectOperation::content::Set(const std::vector<CTableItem>& aContent){
	for(std::vector<CTableItem>::const_iterator it = aContent.begin(); it != aContent.end(); it++){
		if(it->m_strNameColumn == _T("id_journal"))
			s_nIdJournal = _ttoi(it->m_strValueColumn.c_str());
		if(it->m_strNameColumn == _T("is_queen_bee"))
			s_bQueenBee = _ttoi(it->m_strValueColumn.c_str());
		if(it->m_strNameColumn == _T("frame"))
			s_nFrame = _ttoi(it->m_strValueColumn.c_str());
		if(it->m_strNameColumn == _T("strength"))
			s_nStrength = _ttoi(it->m_strValueColumn.c_str());
		if(it->m_strNameColumn == _T("wax"))
			s_nWax = _ttoi(it->m_strValueColumn.c_str());
	}
}